package com.joint.web.action.main;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.dao.jdbc.JdbcDao;
import com.fz.us.base.util.CommonUtil;
import com.fz.us.base.util.DataUtil;
import com.google.common.collect.Lists;
import com.joint.base.entity.Company;
import com.joint.base.entity.system.Admin;
import com.joint.base.service.AdminService;
import com.joint.base.service.CompanyService;
import com.joint.base.service.UsersService;
import com.joint.core.service.ClientService;
import com.joint.core.service.LinkmanService;
import com.joint.core.service.ProInfoService;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * 后台Action类 - 
 * ============================================================================
 * 版权所有 2013 min_xu。
 * ----------------------------------------------------------------------------
 * 
 * @author min_xu
 * 
 * @version 0.1 2013-7-15
 */

@ParentPackage("main")
public class AjaxCompanyAction extends BaseAdminAction {
	private static final long serialVersionUID = -5383463207248344967L;


    @Resource
    private ClientService clientService;
    @Resource
    private LinkmanService linkmanService;
	@Resource
	private UsersService usersService;
	@Resource
	private AdminService adminService;
	@Resource
	private CompanyService companyService;
	@Resource
	private JdbcDao jdbcDao;
	@Resource
	private ProInfoService proInfoService;

	private List<Map<String,String>> listMap;
	private List<Company> list;
	private long start;
	private long end;
	private Company company;
    private Admin admin;
	
	//jqGrid 查询参数
	private String name;
	private String username;

    public String getUsermobile() {
        return usermobile;
    }

    public void setUsermobile(String usermobile) {
        this.usermobile = usermobile;
    }

    private String usermobile;
	
	

	
	public String list(){
		if(page == 0){
			page = 1;
		}
		pager = new Pager();
		pager.setPageSize(LISTVIEW_MP_SIZE);
		pager.setPageNumber(page);
		
		pager = companyService.findByPagerAndCompany(pager, null,null, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
		list = (List<Company>) pager.getList();
		
		return "list";
	}
	
	//jqGrid
	public String jqGrid(){

		pager = new Pager();
		pager.setPageSize(rows);
		pager.setPageNumber(page);
		//pager.setOrderBy("createDate");
		//pager.setOrderType(OrderType.desc);
		
		List<JSONObject> dataRows = new ArrayList<JSONObject>();
		Map<String, Object> data = new HashMap<String, Object>(); 

		Map<String,Object> params = new HashMap<String,Object>();
		params.put("name", name);
		params.put("admin.username", username);
        params.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});

		pager = companyService.findByPager(pager, params, sidx, BaseEnum.OrderType.valueOf(sord));
		
		//	pager = companyService.findByPagerAndCompany(pager, null,null, new StateEnum[]{StateEnum.Enable});
			list = (List<Company>) pager.getList();
			for(Company company:list){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", StringUtils.isNotEmpty(company.getId())?company.getId():"");
				map.put("name", StringUtils.isNotEmpty(company.getName())?company.getName():"");
				map.put("pinYinHead", StringUtils.isNotEmpty(company.getPinYinHead())?company.getPinYinHead():"");
				map.put("pinYin", StringUtils.isNotEmpty(company.getPinYin())?company.getPinYin():"");
				
				Admin a = adminService.get(company.getAdminId());
				map.put("username", a.getUsername());
				map.put("usermobile", CommonUtil.isMobile(a.getUsername())?a.getUsername():a.getUsermobile());
				map.put("expireDate", DataUtil.DateToString(a.getExpireDate()));
				map.put("openId", StringUtils.isEmpty(a.getOpenId())?"否":"是");
				map.put("createDate", DataUtil.DateToString(a.getCreateDate()));
				
				dataRows.add(JSONObject.fromObject(map));
			}
			
			total = pager.getPageCount();
		
		
	    data.put("dataRows", JSONArray.fromObject(dataRows));
	    data.put("records", pager.getTotalCount());
	    data.put("page",page);
	    data.put("rows",rows);
	    data.put("total",total);
		
	    return ajaxJson(JSONObject.fromObject(data).toString());
	}
	
	//jqGrid
	//filters:{"groupOp":"AND","rules":[{"field":"name","op":"bw","data":"1"},{"field":"username","op":"bw","data":"23"}]}
	/**
	 search : {
     caption: "Search...",
     Find: "Find",
     Reset: "Reset",
     odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain']
   },
     企业监控数据
     clientService.getBizDataCount(null, company)
	 * */
	public String jqGridData(){
		pager = new Pager();
		pager.setPageSize(rows);
		pager.setPageNumber(page);
		pager.setOrderBy("createDate");
		pager.setOrderType(BaseEnum.OrderType.desc);
		pager.setOrderBy(sidx);
		pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
		if(org.apache.commons.lang.StringUtils.isNotEmpty(sidx)&&BaseEnum.OrderType.valueOf(sord)!=null){
			pager.setOrderBy(sidx);
			pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
		}
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("name", name);
		params.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
		params = getSearchFilterParams(_search,params,filters);
		pager = companyService.findByPager(pager,params);
		List<Company> companyList;
		if(pager.getTotalCount()==0){
			companyList= Lists.newArrayList();
		}else {
			companyList = (List<Company>) pager.getList();
		}
		List<JSONObject> dataRows = new ArrayList<JSONObject>();
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String,Object> rMap;

		params.clear();
		params.put("state",new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});

		for (Company company:companyList) {
			params.put("company",company);

			rMap = new HashMap<String, Object>();
			rMap.put("id",company.getId());
			rMap.put("name",company.getName());
			rMap.put("phone",adminService.get(company.getAdminId()).getUsermobile());
			rMap.put("createDate", com.joint.base.util.DataUtil.DateToString(company.getCreateDate(), "yyyy-MM-dd"));
			rMap.put("usernum", usersService.findByPager(new Pager(0), params).getList().size());
			rMap.put("pronum", proInfoService.findByPager(new Pager(0),params).getList().size());
			rMap.put("clientnum", clientService.findByPager(new Pager(0),params).getList().size());
			rMap.put("linkmannum", linkmanService.findByPager(new Pager(0), params).getList().size());
			rMap.put("loginuser", usersService.getByAdmin(adminService.get(company.getAdminId())).getName());
			dataRows.add(JSONObject.fromObject(rMap));
		}
		long total =pager.getTotalCount();
		if(total%rows==0){
			total = total/rows;
		}else{
			if(total<rows){
				total = 1;
			}else{
				total = total/rows + 1;
			}
		}
		data.put("dataRows",dataRows);
		data.put("page",page);
		data.put("rows",rows);
		data.put("total",total);
		data.put("records",pager.getTotalCount());
        return ajaxJson(JSONObject.fromObject(data).toString());
    }
		
	public String listData(){
		if(page == 0){
			page = 1;
		}
		pager = new Pager();
		pager.setPageSize(LISTVIEW_MP_SIZE);
		pager.setPageNumber(page);
		
		pager = companyService.findByPagerAndCompany(pager, null,null, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
		list = (List<Company>) pager.getList();

		String users_sql = "SELECT count(*) as perCount from ss_users WHERE company_id = :id and state = 'Enable'";
		String product_sql = "SELECT count(*) as perCount from ss_product WHERE company_id = :id and state = 'Enable'";
		String client_sql = "SELECT count(*) as perCount from ss_client WHERE company_id = :id and (state = 'Enable'  or state = 'History') ";
		String link_sql = "SELECT count(*) as perCount from ss_linkman WHERE company_id = :id and (state = 'Enable'  or state = 'History') ";
		String rese_sql = "SELECT count(*) as perCount from ss_reservation WHERE company_id = :id and (state = 'Enable'  or state = 'History') ";
		String nego_sql = "SELECT count(*) as perCount from ss_negotiation WHERE company_id = :id and (state = 'Enable'  or state = 'History') ";
		String busi_sql = "SELECT count(*) as perCount from ss_business WHERE company_id = :id and (state = 'Enable' or state = 'History') ";
		String cont_sql = "SELECT count(*) as perCount from ss_contract WHERE company_id = :id and (state = 'Enable' or state = 'History') ";
		String pp_sql = "SELECT count(*) as perCount from ss_proceedsplan WHERE company_id = :id and (state = 'Enable' or state = 'History') ";
		
		Map<String,String> filter = new HashMap<String,String>();
		List<Map<String, Object>> tmpListMap;
		
		listMap = new ArrayList<Map<String,String>>();
		
		for(Company company:list){
			Map map = new HashMap<String,String>();
			map.put("id", company.getId());
			map.put("name", company.getName());
			map.put("createDate", DataUtil.DateToString(company.getCreateDate()) );
			
			map.put("usersCount", "0");
			map.put("productCount", "0");
			map.put("clientCount", "0");
			map.put("linkmanCount", "0");
			map.put("reservationCount", "0");
			map.put("negotiationCount", "0");
			map.put("businessCount", "0");
			map.put("contractCount", "0");
			map.put("proceedsPlanCount", "0");
			
			filter.put("id", company.getId());
			
			tmpListMap = jdbcDao.findForListMap(users_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	Map lMap = tmpListMap.get(0);
		    	map.put("usersCount", lMap.get("perCount"));
		    }
		    tmpListMap = jdbcDao.findForListMap(product_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	Map lMap = tmpListMap.get(0);
		    	map.put("productCount", lMap.get("perCount"));
		    }
		    tmpListMap = jdbcDao.findForListMap(client_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	Map lMap = tmpListMap.get(0);
		    	map.put("clientCount", lMap.get("perCount"));
		    }
		    tmpListMap = jdbcDao.findForListMap(link_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	Map lMap = tmpListMap.get(0);
		    	map.put("linkmanCount", lMap.get("perCount"));
		    }
		    tmpListMap = jdbcDao.findForListMap(rese_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	Map lMap = tmpListMap.get(0);
		    	map.put("reservationCount", lMap.get("perCount"));
		    }
		    tmpListMap = jdbcDao.findForListMap(nego_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	Map lMap = tmpListMap.get(0);
		    	map.put("negotiationCount", lMap.get("perCount"));
		    }
		    tmpListMap = jdbcDao.findForListMap(busi_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	Map lMap = tmpListMap.get(0);
		    	map.put("businessCount", lMap.get("perCount"));
		    }
		    tmpListMap = jdbcDao.findForListMap(cont_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	Map lMap = tmpListMap.get(0);
		    	map.put("contractCount", lMap.get("perCount"));
		    }
		    tmpListMap = jdbcDao.findForListMap(pp_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	Map lMap = tmpListMap.get(0);
		    	map.put("proceedsPlanCount", lMap.get("perCount"));
		    }
			listMap.add(map);
		}
		return "listData";
	}
	
	public String dashboard(){
		company = companyService.get(keyId);
		return "dashboard";
	}
	/**
	 * 工作台:单个企业的数据
	 * */
	public String dashboardCount(){

		List<JSONObject> dataRows = new ArrayList<JSONObject>();
		Map<String, Object> rMap = null;
		
		if(start>0&&end>0){
			start = start*1000;
			end = end*1000;
			
			String dateS = DataUtil.DateToString(new Date(start));
			String dateE = DataUtil.DateToString(new Date(end));
			
			String client_sql = "SELECT date_format(createDate, '%Y-%m-%d') as perDate,count(*) as perCount from ss_client WHERE createDate >= :dateS and createDate <= :dateE and (state = 'Enable' or state = 'History') and company_id = :id GROUP BY date_format(createDate, '%Y-%m-%d')";
			String link_sql = "SELECT date_format(createDate, '%Y-%m-%d') as perDate,count(*) as perCount from ss_linkman WHERE createDate >= :dateS and createDate <= :dateE and (state = 'Enable' or state = 'History') and company_id = :id  GROUP BY date_format(createDate, '%Y-%m-%d')";
			String rese_sql = "SELECT date_format(createDate, '%Y-%m-%d') as perDate,count(*) as perCount from ss_reservation WHERE createDate >= :dateS and createDate <= :dateE and (state = 'Enable' or state = 'History') and company_id = :id  GROUP BY date_format(createDate, '%Y-%m-%d')";
			String nego_sql = "SELECT date_format(createDate, '%Y-%m-%d') as perDate,count(*) as perCount from ss_negotiation WHERE createDate >= :dateS and createDate <= :dateE and (state = 'Enable' or state = 'History') and company_id = :id  GROUP BY date_format(createDate, '%Y-%m-%d')";
			String busi_sql = "SELECT date_format(createDate, '%Y-%m-%d') as perDate,count(*) as perCount from ss_business WHERE createDate >= :dateS and createDate <= :dateE and (state = 'Enable' or state = 'History') and company_id = :id  GROUP BY date_format(createDate, '%Y-%m-%d')";
			String cont_sql = "SELECT date_format(createDate, '%Y-%m-%d') as perDate,count(*) as perCount from ss_contract WHERE createDate >= :dateS and createDate <= :dateE and (state = 'Enable' or state = 'History') and company_id = :id  GROUP BY date_format(createDate, '%Y-%m-%d')";
			String pp_sql = "SELECT date_format(createDate, '%Y-%m-%d') as perDate,count(*) as perCount from ss_proceedsplan WHERE createDate >= :dateS and createDate <= :dateE and (state = 'Enable' or state = 'History') and company_id = :id  GROUP BY date_format(createDate, '%Y-%m-%d')";
			
			Map<String,String> filter = new HashMap<String,String>();
			filter.put("dateS", dateS);
			filter.put("dateE", dateE);
			filter.put("id", keyId);
			
			List<Map<String, Object>> tmpListMap;
			tmpListMap = jdbcDao.findForListMap(client_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	for(Map lMap:tmpListMap){
		    		String perDate = (String)lMap.get("perDate");
		    		Long perCount = (Long)lMap.get("perCount");
		    		
		    		rMap = new HashMap<String, Object>();
					rMap.put("title", "1[新增客户数] " + perCount);
					rMap.put("start", perDate);
					rMap.put("className", "['event', 'bg-color-blue']");
					rMap.put("icon", "fa-credit-card");
					
					dataRows.add(JSONObject.fromObject(rMap));
		    	}
		    }
		    tmpListMap = jdbcDao.findForListMap(link_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	for(Map lMap:tmpListMap){
		    		String perDate = (String)lMap.get("perDate");
		    		Long perCount = (Long)lMap.get("perCount");
		    		
		    		rMap = new HashMap<String, Object>();
					rMap.put("title", "2[新增联系人数] " + perCount);
					rMap.put("start", perDate);
					rMap.put("className", "['event', 'bg-color-teal']");
					rMap.put("icon", "fa-user");
					
					dataRows.add(JSONObject.fromObject(rMap));
		    	}
		    }
		    tmpListMap = jdbcDao.findForListMap(rese_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	for(Map lMap:tmpListMap){
		    		String perDate = (String)lMap.get("perDate");
		    		Long perCount = (Long)lMap.get("perCount");
		    		
		    		rMap = new HashMap<String, Object>();
					rMap.put("title", "3[新增预约数] " + perCount);
					rMap.put("start", perDate);
					rMap.put("className", "['event', 'bg-color-pink']");
					rMap.put("icon", "fa-clock-o");
					
					dataRows.add(JSONObject.fromObject(rMap));
		    	}
		    }
		    tmpListMap = jdbcDao.findForListMap(nego_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	for(Map lMap:tmpListMap){
		    		String perDate = (String)lMap.get("perDate");
		    		Long perCount = (Long)lMap.get("perCount");
		    		
		    		rMap = new HashMap<String, Object>();
					rMap.put("title", "4[新增洽谈数] " + perCount);
					rMap.put("start", perDate);
					rMap.put("className", "['event', 'bg-color-greenDark']");
					rMap.put("icon", "fa-comments");
					
					dataRows.add(JSONObject.fromObject(rMap));
		    	}
		    }
		    tmpListMap = jdbcDao.findForListMap(busi_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	for(Map lMap:tmpListMap){
		    		String perDate = (String)lMap.get("perDate");
		    		Long perCount = (Long)lMap.get("perCount");
		    		
		    		rMap = new HashMap<String, Object>();
					rMap.put("title", "5[新增业务数] " + perCount);
					rMap.put("start", perDate);
					rMap.put("className", "['event', 'bg-color-purple']");
					rMap.put("icon", "fa-check-square");
					
					dataRows.add(JSONObject.fromObject(rMap));
		    	}
		    }
		    tmpListMap = jdbcDao.findForListMap(cont_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	for(Map lMap:tmpListMap){
		    		String perDate = (String)lMap.get("perDate");
		    		Long perCount = (Long)lMap.get("perCount");
		    		
		    		rMap = new HashMap<String, Object>();
					rMap.put("title", "6[新增成交数] " + perCount);
					rMap.put("start", perDate);
					rMap.put("className", "['event', 'bg-color-green']");
					rMap.put("icon", "fa-flag");
					
					dataRows.add(JSONObject.fromObject(rMap));
		    	}
		    }
		    tmpListMap = jdbcDao.findForListMap(pp_sql,filter);
		    if(null != tmpListMap && tmpListMap.size()>0) {
		    	for(Map lMap:tmpListMap){
		    		String perDate = (String)lMap.get("perDate");
		    		Long perCount = (Long)lMap.get("perCount");
		    		
		    		rMap = new HashMap<String, Object>();
					rMap.put("title", "7[新增履约数] " + perCount);
					rMap.put("start", perDate);
					rMap.put("className", "['event', 'bg-color-orange']");
					rMap.put("icon", "fa-star");
					
					dataRows.add(JSONObject.fromObject(rMap));
		    	}
		    }
		}
		
		return ajaxJson(JSONArray.fromObject(dataRows).toString());
	}




	public List<Map<String, String>> getListMap() {
		return listMap;
	}

	public void setListMap(List<Map<String, String>> listMap) {
		this.listMap = listMap;
	}

	public Admin getAdmin() {
		return admin;
	}

	public void setAdmin(Admin admin) {
		this.admin = admin;
	}


	public List<Company> getList() {
		return list;
	}


	public void setList(List<Company> list) {
		this.list = list;
	}


	public long getStart() {
		return start;
	}


	public void setStart(long start) {
		this.start = start;
	}


	public long getEnd() {
		return end;
	}


	public void setEnd(long end) {
		this.end = end;
	}


	public Company getCompany() {
		return company;
	}


	public void setCompany(Company company) {
		this.company = company;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}


	public String getUsername() {
		return username;
	}


	public void setUsername(String username) {
		this.username = username;
	}




}
